package io.renren.modules.api.controller;

import io.renren.common.utils.*;
import io.renren.common.validator.Assert;
import io.renren.modules.api.annotation.AuthIgnore;
import io.renren.modules.api.entity.UsertokenEntity;
import io.renren.modules.api.interceptor.AuthorizationInterceptor;
import io.renren.modules.api.service.UsertokenService;
import io.renren.modules.areainfos.service.AreainfosService;
import io.renren.modules.dictionary.entity.DictionaryEntity;
import io.renren.modules.dictionary.service.DictionaryService;
import io.renren.modules.footprint.entity.VipfootprintinfosEntity;
import io.renren.modules.footprint.service.VipfootprintinfosService;
import io.renren.modules.projectinfo.entity.ProjectinfosCustomEntity;
import io.renren.modules.projectinfo.entity.ProjectinfosEntity;
import io.renren.modules.projectinfo.service.ProjectinfosService;
import io.renren.modules.user.service.UserinfosService;
import io.renren.modules.vipuser.service.VipinfosService;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: stf
 * @description: 项目api
 * @author: Custom
 * @create: 2018-10-31 13:07
 **/

@RestController
@RequestMapping("/api/project")
public class ApiProjectController{

    @Autowired
    private UsertokenService tokenService;

    @Autowired
    private UserinfosService userinfosService;

    @Autowired
    private VipinfosService vipinfosService;

    @Autowired
    private ProjectinfosService projectinfosService;

    @Autowired
    private VipfootprintinfosService vipfootprintinfosService;

    @Autowired
    private AreainfosService areainfosService;

    @Autowired
    private DictionaryService dictionaryService;



    @GetMapping("/myprojects")
    public R getMyProjects(@RequestParam Map<String, Object> params,HttpServletRequest request){
        //设置分页的默认值和限制分页数量内容
        CustomUtils.judgePageParams(params);
        //设置用户
        //获取用户
        String userinfoid = (String) request.getAttribute(AuthorizationInterceptor.USER_KEY);
        params.put("createuser",userinfoid);
        //查询列表数据
        Query query = new Query(params);

        List<ProjectinfosCustomEntity> projectinfosList = projectinfosService.queryApiMyList(query);
        int total = projectinfosService.queryApiMyTotal(query);
        PageUtils pageUtil = new PageUtils(projectinfosList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);
    }

    @PostMapping("exist")
    public R isProjectExistByUser(String projectinfoid,HttpServletRequest request){
        //获取用户id
        String userinfoid = (String) request.getAttribute(AuthorizationInterceptor.USER_KEY);
        Map<String,Object> map = new HashMap<>();
        map.put("projectinfoid",projectinfoid);
        map.put("userinfoid",userinfoid);
        R projectExistByUser = projectinfosService.isProjectExistByUser(map);
        if(projectExistByUser != null){
            return R.ok().put("msg","未拥有此项目！").put("state",0);
        }
        return R.ok().put("state",1);
    }

    //获取工程简介信息列表
    @AuthIgnore
    @GetMapping("/list")
    public R getProjectDescList(@RequestParam Map<String, Object> params){
        //防止通过用户id来查询我的项目（因为用的同一个sql）
        if(params.containsKey("userinfoid")){
            params.remove("userinfoid");
        }
        //根据地区搜索
        CustomUtils.setSearchByArea(params,areainfosService);
        //设置项目类型的默认值
        if(params.containsKey("projecttype")){
            int projecttype = Integer.parseInt((String)params.get("projecttype"));
            if(projecttype != 0 && projecttype != 1){
                params.put("projecttype","0");
            }
        }else {
            params.put("projecttype","0");
        }
        //设置分页的默认值和限制分页数量内容
        CustomUtils.judgePageParams(params);

        //查询列表数据
        Query query = new Query(params);
        List<ProjectinfosCustomEntity> projectinfosList = projectinfosService.queryApiList(query);
        int total = projectinfosService.queryApiTotal(query);
        PageUtils pageUtil = new PageUtils(projectinfosList, total, query.getLimit(), query.getPage());
        return R.ok().put("page", pageUtil);

    }

    //获取工程详细信息
    @AuthIgnore
    @GetMapping("info/{projectinfoid}")
    public R getProjectDetailInfo(@PathVariable("projectinfoid") String projectinfoid,HttpServletRequest request) {
        if(projectinfoid == null){
            return R.error("不能为空哦！");
        }
        //先查寻到信息
        ProjectinfosCustomEntity projectinfosCustomEntity = projectinfosService.queryApiInfo(projectinfoid);
        if(projectinfosCustomEntity == null){
            return R.error("项目不存在");
        }
        //验证是否为自己的项目
        //获取用户
        String userid = getUserId(request);
        if(isHave(userid,projectinfoid)){
            //用户拥有项目
            return R.ok().put("data",projectinfosCustomEntity);
        }
        //项目是否通过
        R projectAuditSucceed = projectinfosService.judgeProjectAuditSucceed(projectinfoid);
        if(projectAuditSucceed != null){
            return projectAuditSucceed;
        }


        //清空联系电话
        projectinfosCustomEntity.setConnection(null);
        return R.ok().put("data", projectinfosCustomEntity);
    }

    @PostMapping("/contact")
    public R getContact(String projectinfoid,HttpServletRequest request){


        //获取用户
        String userid = getUserId(request);
        //如果用户为空，则不返回电话号码
        if (userid == null) {
            return R.error("用户不存在!");
        }

        //获取联系信息
        String connectionInfo = projectinfosService.queryConnectionInfo(projectinfoid);

        //用户拥有项目，即全部返回
        if (isHave(userid, projectinfoid)) {
            return R.ok().put("data",connectionInfo);
        }

        //项目是否通过
        R projectAuditSucceed = projectinfosService.judgeProjectAuditSucceed(projectinfoid);
        if(projectAuditSucceed != null){
            return projectAuditSucceed;
        }

        //浏览项目所需积分
        DictionaryEntity browseIntegralDic = dictionaryService.queryObjectByDateTypeName("BrowseIntegral");

        //保存最后结果
        BigDecimal result = new BigDecimal(browseIntegralDic.getDictionaryvalue());

        //为vip
        if(userinfosService.isVip(userid)){
            //获取优惠值
            DictionaryEntity vipDiscountDic = dictionaryService.queryObjectByDateTypeName("VIPDiscount");
            BigDecimal vipDiscount = new BigDecimal(vipDiscountDic.getDictionaryvalue());
            BigDecimal  percent = new BigDecimal("0.1");
            vipDiscount = vipDiscount.multiply(percent);
            //最后价格
            result = vipDiscount.multiply(result);
        }

        //扣除积分
        boolean b = userinfosService.reduceTheIntegral(userid, result);
        //如果成功，则添加到足迹中
        if(b){
            //添加到足迹表
            VipfootprintinfosEntity vipfootprintinfosEntity = new VipfootprintinfosEntity();
            vipfootprintinfosEntity.setTargetid(projectinfoid);
            vipfootprintinfosEntity.setUserinfoid(userid);
            vipfootprintinfosService.save(vipfootprintinfosEntity);
            return R.ok().put("data",connectionInfo);
        }
        return R.error("您的积分不足!");

       /* if(projectinfoid == null){
            return R.error("没有找到此项目");
        }
        //项目是否通过
        R projectAuditSucceed = projectinfosService.judgeProjectAuditSucceed(projectinfoid);
        if(projectAuditSucceed != null){
            return projectAuditSucceed;
        }
        //获取用户
        String userid = getUserId(request);
        //如果用户为空，则不返回电话号码
        if (userid == null) {
            return R.error("用户不存在!");
        }
        String connectionInfo = projectinfosService.queryConnectionInfo(projectinfoid);
        //用户不拥有时
        if (!isHave(userid, projectinfoid)) {
            //用户不拥有项目：1.验证浏览次数，2.成功：减次数，添加到足迹表
            //判断用户是否有权限获取项目详细信息

            //如果是vip，则把项目添加到足迹中
            if(userinfosService.isVip(userid)){
                if(!vipinfosService.updateVipUserBrowTimes(userid)){
                    return R.error("您的浏览次数不足!");
                }
                //添加到足迹表
                VipfootprintinfosEntity vipfootprintinfosEntity = new VipfootprintinfosEntity();
                vipfootprintinfosEntity.setTargetid(projectinfoid);
                vipfootprintinfosEntity.setUserinfoid(userid);
                vipfootprintinfosService.save(vipfootprintinfosEntity);
            }else {
                if(!userinfosService.reduceTheIntegral(userid,1)){
                    return R.error("您的浏览次数不足!");
                }
            }
        }
        return R.ok().put("data",connectionInfo);*/
    }

    public boolean isHave(String userid,String projectinfoid) {
        //如果用户不为空，用户足迹表中存在该项目id，则返回所有信息
        //如果，该项目是本用户的项目，则返回全部信息
        VipfootprintinfosEntity vipfootprintinfosEntity = new VipfootprintinfosEntity();
        vipfootprintinfosEntity.setUserinfoid(userid);
        vipfootprintinfosEntity.setTargetid(projectinfoid);
        ProjectinfosEntity projectinfosEntity = new ProjectinfosEntity();
        projectinfosEntity.setCreateuser(userid);
        projectinfosEntity.setProjectinfoid(projectinfoid);
        //验证用户是否拥有该项目或者该用户购买了该项目
        Map<String,Object> map = new HashMap<>();
        map.put("userinfoid",userid);
        map.put("projectinfoid",projectinfoid);
        R projectExistByUser = projectinfosService.isProjectExistByUser(map);
        if (projectExistByUser == null || vipfootprintinfosService.judgeFoodprintExistByUser(vipfootprintinfosEntity) == null) {
            //存在,返回所有数据
            return true;
        } else {//不是本人项目，或购买项目
            return false;
        }


    }

    //发布项目（工程，车队）
    @PostMapping("/release")
    public R releaseProject(ProjectinfosEntity projectinfos,HttpServletRequest request){


        if(projectinfos == null){
            return R.error("不能为空哦！");
        }
        //添加pojo属性验证
        Assert.isBlank(projectinfos.getProjectname(),"项目名不能为空！");
        Assert.isBlank(projectinfos.getDescription(),"项目说明不能为空！");
        Assert.isNull(projectinfos.getAreainfoid(),"项目说明不能为空！");
        Assert.isBlank(projectinfos.getDetailedaddress(),"详细地址不能为空！");
        Assert.isBlank(projectinfos.getConnection(),"详细信息不能为空！");
        Assert.isNull(projectinfos.getProjecttype(),"项目类型不能为空！");
        Assert.isNull(projectinfos.getPeoplenum(),"项目人数不能为空！");

        //项目类型标识验证
        R projectyTypeError = projectinfosService.judgeProjectTypeError(projectinfos.getProjecttype());
        if(projectyTypeError != null){
            return projectyTypeError;
        }
        //地区标识验证
        R areaError = areainfosService.isExistArea(projectinfos.getAreainfoid());
        if(areaError != null){
            return areaError;
        }

        //获取当前用户
        String userinfoid = (String) request.getAttribute(AuthorizationInterceptor.USER_KEY);

        //积分限制
        //发布项目所需积分
        DictionaryEntity browseIntegralDic = dictionaryService.queryObjectByDateTypeName("ReleaseIntegral");

        //保存最后结果
        BigDecimal result = new BigDecimal(browseIntegralDic.getDictionaryvalue());

        //为vip
        if(userinfosService.isVip(userinfoid)){
            //获取优惠值
            DictionaryEntity vipDiscountDic = dictionaryService.queryObjectByDateTypeName("VIPDiscount");
            BigDecimal vipDiscount = new BigDecimal(vipDiscountDic.getDictionaryvalue());
            BigDecimal  percent = new BigDecimal("0.1");
            vipDiscount = vipDiscount.multiply(percent);
            //最后价格
            result = vipDiscount.multiply(result);
        }

        //扣除积分
        boolean b = userinfosService.reduceTheIntegral(userinfoid, result);
        if(b){
            //发布项目
            //设置发布者
            projectinfos.setCreateuser(userinfoid);
            //判错
            projectinfosService.releaseApiProject(projectinfos);
            return R.ok().put("msg","发布成功，等待审核");
        }
        return R.error("您的积分不足!");

    }

    //更新工程信息
    @PostMapping("/update")
    public R updateProject(ProjectinfosEntity projectinfos,HttpServletRequest request){
        if(projectinfos == null){
            return R.error("不能为空哦！");
        }
        //获取用户id
        String userinfoid = (String) request.getAttribute(ConstantUtils.USER_KEY);
        //设置发布者
        projectinfos.setCreateuser(userinfoid);
        //判断当前用户是否为项目拥有者
        Map<String,Object> map = new HashMap<>();
        map.put("userinfoid",userinfoid);
        map.put("projectinfoid",projectinfos.getProjectinfoid());
        R projectExistByUserError = projectinfosService.isProjectExistByUser(map);
        if(projectExistByUserError != null){
            return projectExistByUserError;
        }
        //pojo属性验证
        Assert.isBlank(projectinfos.getProjectname(),"项目名不能为空！");
        Assert.isBlank(projectinfos.getDescription(),"项目说明不能为空！");
        Assert.isNull(projectinfos.getAreainfoid(),"项目说明不能为空！");
        Assert.isBlank(projectinfos.getDetailedaddress(),"详细地址不能为空！");
        Assert.isBlank(projectinfos.getConnection(),"详细信息不能为空！");
        Assert.isNull(projectinfos.getProjectprogress(),"项目进度不能为空！");
        Assert.isNull(projectinfos.getPeoplenum(),"项目人数不能为空！");

        //更新时,无法修改项目进度已完工的项目
        if (projectinfosService.queryProgress(projectinfos.getProjectinfoid()) == 1){
            return R.error("项目已完工，无法修改！");
        }
        //项目进度验证
        R progressError= projectinfosService.judgeProgressError(projectinfos.getProjectprogress());
        if(progressError != null){
            return progressError;
        }
        //项目地区验证
        R areaError = areainfosService.isExistArea(projectinfos.getAreainfoid());
        if(areaError != null){
            return areaError;
        }
        projectinfosService.updateApiProject(projectinfos);
        return R.ok().put("msg","修改成功，等待审核！");
    }

    //删除工程信息
//    @PostMapping("/deletes")
//    public R delete(String projectids, HttpServletRequest request){
//        //获取用户
//        String userinfoid = (String) request.getAttribute(AuthorizationInterceptor.USER_KEY);
//        //删除项目
//        String[] split = projectids.split(",");
//        Map<String,Object> map = new HashMap<>(16);
//        map.put("createuser",userinfoid);
//        map.put("projectids",split);
//        int i = projectinfosService.apiDeletes(map);
//        if(i == 0){
//            return R.error("项目不存在,删除失败！");
//        }
//        return R.ok().put("msg","成功删除"+i+"条！");
//    }

    //删除工程信息
    @PostMapping("/deletes")
    public R delete(String projectids, HttpServletRequest request){
        //获取用户
        String userinfoid = (String) request.getAttribute(AuthorizationInterceptor.USER_KEY);
        //删除项目
        String[] split = projectids.split(",");
        Map<String,Object> map = new HashMap<>(16);
        map.put("createuser",userinfoid);
        map.put("projectids",split);
        int i = projectinfosService.apiSoftDelete(map);
        if(i == 0){
            return R.error("项目不存在,删除失败！");
        }
        return R.ok().put("msg","成功删除"+i+"条！");
    }


    private String getUserId(HttpServletRequest request) {
        //从header中获取token
        String token = request.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter("token");
        }
        //token为空
        if(StringUtils.isBlank(token)){
            return null;
        }
        //查询token信息
        UsertokenEntity tokenEntity = tokenService.queryByToken(token);
        if(tokenEntity == null || tokenEntity.getExpiredate().getTime() < System.currentTimeMillis()){
            return null;
        }
        //设置userId到request里，后续根据userId，获取用户信息
        return tokenEntity.getUserinfoid();
    }

}
